/**
 * SpreadSheetObserver.java
 */
package com.pluginsacceptor.plugin.spreadsheet;

import java.awt.Color;
import java.awt.Font;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JTable;

import org.apache.log4j.Logger;

import com.pluginsacceptor.plugin.spreadsheet.model.Cell;
import com.pluginsacceptor.utils.CommunicationUtils;

/**
 * The class contains method for update font size from another plugin
 */
public class SSObserver implements Observer {

    /** Logger */
    private static final Logger LOG = Logger.getLogger(SSObserver.class);

    /** */
    private final JTable ssTable;

    /**
     * Constructor
     * @param ssTable the spread sheet table
     */
    public SSObserver(final JTable ssTable) {
        super();
        this.ssTable = ssTable;
    }

    @Override
    public void update(final Observable observable, final Object externalData) {
        if (externalData instanceof String) {
            final String cellString = (String) externalData;
            try {
                parseData(cellString);
            } catch (final Exception e) {
                LOG.warn("Unexpected message format '" + cellString + "'", e);
            }
        }

    }

    /**
     * Parse source data string
     * @param cellString the source data string
     */
    private void parseData(final String cellString) {

        final int col = CommunicationUtils.getColNumFromCellString(cellString);
        final int row = CommunicationUtils.getRowNumFromCellString(cellString);

        if (CommunicationUtils.isCellData(cellString)) {
            this.ssTable.getModel().setValueAt(
                new Cell(CommunicationUtils.getValueFromCellString(cellString)),
                row,
                col
            );
        } else {
            final Cell cell = ((Cell) this.ssTable.getModel().getValueAt(row, col));
            final String fontType = CommunicationUtils.getFontFromCellString(cellString);
            final Color color = CommunicationUtils.getColorFromCellString(cellString);

            final Font font = cell.getFont();
            final Color currentColor = cell.getForeground();
            switch (fontType) {
                case "Bold":
//                    cell.setFont(font.deriveFont(font.isBold() ? Font.PLAIN : Font.BOLD));
                    cell.setFont(font.deriveFont(Font.BOLD));
                    break;
                case "Italic":
//                    cell.setFont(font.deriveFont(font.isItalic() ? Font.PLAIN : Font.ITALIC));
                    cell.setFont(font.deriveFont(Font.ITALIC));
                    break;
                case "Plain":
                    cell.setFont(font.deriveFont(Font.PLAIN));
                    break;
                default:
                    break;
            }

            if (color != null && !currentColor.equals(color)) {
                cell.setForeground(color);
            }

            this.ssTable.repaint();
        }
    }
}
